<template>
	<div>
		<head-top></head-top>
		<div class="boxWrap">
			<div class="createTemplate clearfix">
				<div class="alert alert-success" v-if="saveSuccess" style="background-color: #dff0d8;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>成功！</strong>操作成功。
				</div>
				<div class="alert alert-danger" v-if="saveError" style="background-color: #f2dede;">
					<a href="#" class="close" data-dismiss="alert">&times;</a>
					<strong>{{errorTip}}！</strong>
				</div>
				<div class="left createTemplate_left">
					<div style="margin-bottom:20px;">
						<!--<p class="createTemplate_words text-left">读取类型</p>-->
						<!--<p class="read_type">
							<span v-for='(data,key,index) in readTypes' v-on:click="addClassFun(index)" v-bind:class='{read_type_style:index==addClassIndex}'>{{data.data}}</span>
						</p>-->
						<p class="text-left">
							<button class="btn choose_data_btn" @click="chooseData()">选择测试数据</button>
						</p>
					</div>
					<div class="clearfix">
						<span class="createTemplate_words left">输入数据是否要求标签</span>
						<label class="right createTemplate_words" style="font-weight:normal;"  v-show="diff_model_tem">
					        <input class="input_checkbox" type="checkbox" name="header_checkbox" @change="changeHeaderState()" v-model="checkHeader">
					        <span class="input_checkboxInput" style="margin-right:0;"></span>
						</label>
					</div>
					<div class="contain_tags text-left" v-if="containTags">
						<input type="text" placeholder="标签名" class="contain_input" v-model="labelName"/>
						<select name="data_header" v-model="selected_data">
		        			<option v-for="option_data in options_data" v-bind:value="option_data.value">{{ option_data.text }}</option>
		        		</select>
					</div>
					<div class="clearfix" style="margin-top:20px;">
						<span class="createTemplate_words left" @click="test()">添加输入特征</span>
						<img src="../assets/img/add.png" alt="add" class="cursor right" @click="addFeaturesItem()" style="width:18px;height:18px;"/>
					</div>
					<!--添加其他特征-->
					<div class="text-left contain_tags features_box" v-for="(v,i) in other_features_list">
						<input type="text" placeholder="特征名" class="contain_input addFeatures" />
						<select name="data_feature" class="feature_val">
		        			<option v-for="option_feature in options_feature" v-bind:value="option_feature.value">{{ option_feature.text }}</option>
		        		</select>
					</div>
					<!--超参数列表-->
					<div v-show="diff_model_tem">
						<div class="clearfix" style="margin-top:20px;">
							<span class="createTemplate_words left">添加模板超参数</span>
							<img src="../assets/img/add.png" alt="add" class="cursor right" @click="addParameterItem(2)"  style="width:18px;height:18px;"/>
						</div>
						<table>
							<tr>
	                            <th>名称</th>
	                            <th>类型</th>
	                            <th>默认值</th>
	                        </tr>
					        <tr v-for="item in hyperParameterArr" class="text-left">
					            <td>{{item.name}}</td>
					            <td>{{item.selected}}</td>
					            <td>{{item.default}}</td>
					        </tr>
					    </table>
					</div>
				</div>
				<div class="left online_editor">
					<p class="text-left" style="margin-bottom:30px;">
						<span class="temp_title">模{{tem_or_model_name}}名称&nbsp;&nbsp;</span>
						<input type="text"  v-model="inputTemName" class="data_info_name_val" style="font-size:18px;"/>
					</p>
					<div class="clearfix editor_operation" >
						<p class="text-left left" style="font-size:16px;line-height:24px;">在线编辑</p>
						<button class="right btn" @click="_blankNotebook()">Jupyter</button>
						<!--<button class="right btn" disabled="disabled" @click="showSave(2)">发布</button>-->
						<button class="right btn saveTemBtn" @click="showSave(1)">保存</button>
						<button class="right btn testTemBtn" @click="testTemplate()">测试</button>
					</div>
					<p>
<pre id="code" class="ace_editor" style="min-height:400px;width:918px;"><textarea class="ace_text-input"># -*-coding:utf-8-*-
import pickle
from base_node import BaseNode
from sklearn.externals import joblib

class YourNode(BaseNode):
   """
   class的命名必须符合正则表达式:[a-zA-Z]+[a-zA-Z0-9_]+Node,且必须继承BaseNode,否则代码可能无法正确执行
   """

   def __init__(self, params, data_meta):
       """
       该方法必须实现
       初始化，您可以在此获得您在执行代码前设置的参数和超参数
       :param params: 您设置的参数，由系统自动传入，请勿更改
       :param data_meta: 您设置的超参数，由系统自动传入，请勿更改
       """
       pass

   def train(self):
       """
       如果您需要训练模型，请实现该方法
       :return:
       """
       pass

   def test(self):
       """
       如果您需要测试您的代码，请实现该方法
       :return:
       """
       print 'hello world'

   def save_model(self, model, filename):
       """
       保存训练出的模型参数，如非必要请勿修改该方法
       :param model: 训练出的模型参数
       :param filename: 一般为.pkl文件但不强制,但必须保存在当前文件夹内
       :return:
       """
       file_path = './'+str(filename)
       joblib.dump(model, file_path, compress=3)

   def read_model(self, filename):
       """
       读取训练产生的模型参数用于预测，如非必要请勿修改该方法
       :param filename: 模型训练所得参数，由系统自动传入请勿更改
       :return: joblib模块加载后的对象
       """
       return joblib.load(filename)


   def run(self):
       """
       如果您需要使用训练好的模型做预测，请实现该方法
       :return:
       """
       pass
       </textarea></pre>
					</p>
					<div class="operation_result">
						<p class="text-left">运行结果</p>
						<textarea class="run_result">{{runResult}}</textarea>
					</div>
				</div>
			</div>
		</div>
		<footerHtml></footerHtml>
		<div id="mask" v-if="seen"></div>
		<!--选择数据-->
		<div class="bomb_box" v-if="bombChooseData" style="margin-left:-450px;font-size:14px;">
			<p class="text-left">
				<label class="input_label_beautify">
			        <input class="input_radio" type="checkbox" name="build_checkbox">
			        <span class="input_checkbox input_radioInput"></span>只看我的数据
				</label>
			</p>
			<table class="table table-striped table-hover table-bordered" id="detail_table" >
	            <thead>
	                <tr>
	                    <th>数据名称</th>
	                    <th>数据描述</th>
	                    <th>创建者</th>
	                    <th>创建时间</th>
	                    <th>操作</th>
	                </tr>
	            </thead>
	            <tbody>
	            	<tr v-for="data_item in dataAll.data_all_list" v-if="dataAll.data_all_list.length!=0" class="text-left">
	                    <td>{{data_item.title}}</td>
	                    <td class="p_words" style="width:10%;">{{data_item.description}}</td>
	                    <td>{{data_item.creator}}</td>
	                    <td>{{data_item.create_time}}</td>
	                    <td>
	                        <label class="input_label_beautify">
						        <input class="input_radio" type="radio" name="dash_checkbox"  v-on:click="changeDataId(data_item.id)" :id="data_item.id">
						        <span class="input_radioInput"></span>
							</label>
	                    </td>
	              	</tr>
	              	<tr v-else>
	                	<td colspan="5">暂时无数据列表</td>
	                </tr>
	            </tbody>
	        </table>
	       	<v-pagination :total="dataAll.total"  :current-page='dataAll.current' @pagechange="pagechange" ></v-pagination>
			<p  class="text-right" style="margin-top:60px;">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="btn data_edit_sure"  @click="compSelection()">确定</button>
			</p>
		</div>
		<!--设置参数-->
		<div class="bomb_box bomb_setting_parameters" v-if="seenSet">
			<p>设置超参数</p>
			<p class="data_info_tip" v-if="floatIntTip">{{typeTipMsg}}</p>
			<p class="text-center">
				<span class="data_info_name">名称</span>
				<input type="text" class="setting_parameters_val" v-model="fillInName"/>
			</p>
			<p class="text-center">
				<span class="data_info_name">类型</span>
				<select name="" v-model="selected">
        			<option v-for="option in options" v-bind:value="option.value">{{ option.text }}</option>
        		</select >
			</p>
			<!--如果是string-->
			<div  v-if="selected==0">
				<p class="text-center ">
					<span class="data_info_name">默认</span>
					<input type="text" class="setting_parameters_val" v-model="fillInDefault"/>
				</p>
				<p class="text-center">
					<span class="data_info_name">范围</span>
					<input type="text" class="setting_parameters_val"  v-model="fillInRange" placeholder="范围之间请用逗号连接"/>
				</p>
			</div>
			<!--如果是float-->
			<div v-if="selected==1">
				<p class="text-center">
					<span class="data_info_name">默认</span>
					<input  class="setting_parameters_val" v-model="fillInDefault" placeholder="浮点数或者0" @blur="pregFloat()"/>
				</p>
				<p class="text-center">
					<span class="data_info_name">最小</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMin" @blur="pregFloat()"/>
				</p>
				<p class="text-center ">
					<span class="data_info_name">最大</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMax" @blur="pregFloat()"/>
				</p>
			</div>
			<!--如果是integer-->
			<div v-if="selected==2">
				<p class="text-center">
					<span class="data_info_name">默认</span>
					<input type="number" class="setting_parameters_val" v-model="fillInDefault" placeholder="整数或者0" @blur="pregInt()"/>
				</p>
				<p class="text-center">
					<span class="data_info_name">最小</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMin" @blur="pregInt()"/>
				</p>
				<p class="text-center ">
					<span class="data_info_name">最大</span>
					<input type="number" class="setting_parameters_val" v-model="fillInMax" @blur="pregInt()"/>
				</p>
			</div>
			<!--如果是boolean-->
			<div v-if="selected==3" class="text-left">
				<span style="margin-left:30px;" class="data_info_name">默认</span>
				<label class="input_label">
			        <input class="input_radio setting_parameters_val" type="radio" name="param_checkbox_selsect" @click="changeFillDefaultT()">
			        <span class="input_checkbox input_radioInput"></span>true
				</label>
				<label class="input_label">
			        <input class="input_radio setting_parameters_val" type="radio" name="param_checkbox_selsect" @click="changeFillDefaultF()">
			        <span class="input_checkbox input_radioInput"></span>false
				</label>
			</div>
			<p  class="text-right" style="margin-top:10px;">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="data_info_sure btn" @click="synchronization()">确定</button>
			</p>
		</div>
		<!--创建模板/模型的弹框-->
		<div class="bomb_box" v-if="showSaveTem">
			<p>创建模板</p>
			<p class="data_info_tip" v-if="seenTemTip">请检查填写信息!</p>
			<p class="text-left">
				<span class="data_info_name" style="display: block; float: left;">描述</span>
				<textarea name="des" class="data_info_des_val editDes" v-model="inputTemDes" style="width:450px;"></textarea>
			</p>
			<p  class="text-right" style="margin-top:40px;">
				<button class="btn data_info_cancel" @click="bombBoxHide()">取消</button>
				<button class="btn data_edit_sure" @click="SaveOrReleaseTemplate()" style="margin-left:40px;">确定</button>
			</p>
		</div>
	</div>

</template>

<script>
import Vue from 'vue'
import { bus } from '../assets/js/bus.js'
//引入公共模块
import headTop from '@/components/headTop'
import editor from '@/components/editor'
import footerHtml from '@/components/footerHtml'
import pagination from '@/components/page'
import global_ from '@/components/global'

//api
import {urlSaveTemplate,urlTestTemplate,urlGetDetail,urlDashDataList,urlUpdateTemplate,urlNotebook} from '../api/api'

export default {
    name: 'createTemplate',
    data(){
    	return {
    		//判别入门
    		tem_or_model_name:'板',
    		show_save:'',
    		path:'',
    		typeTipMsg:'',
    		//结束
    		runResult:'none',
    		templateId:'',
    		checkHeader:'',
    		headerState:0,
    		editVis:0,
    		containTags:false,
    		seen:false,
    		seenSet:false,
    		typeNumber:false,
    		typeOther:true,
    		saveSuccess:false,
    		saveError:false,
    		showSaveTem:false,
    		seenTemTip:false,
    		bombChooseData:false,
    		diff_model_tem:false,
    		floatIntTip:false,
    		labelName:'',
    		errorTip:'',
			fillInName:'',
			fillInDefault:'',
			fillInMax:'',
			fillInMin:'',
			fillInRange:'',
			inputTemName:'TemplateName',
			inputTemDes:'',
			dataAll:{
	    		data_all_list:'',
        		total:5,
        		page_num:1,
        		current:1,
        		filter:0,
    		},
    		change_data_id:'',
    		other_features_list:[
//  			{a: '', b: ''}
    		],
			hyperParameterArr:[],
			parameterArr:[],
			hyper_param_spec:{},
			param_spec:{},
			resProperties:'',
			addCode:'',
    		features: [
                '+添加'
           	],
           	sv:'+添加',
           	readTypes: {
				data1: {
					data: "Excel"
				},
				data2: {
					data: "CSV"
				}
			},
			addClassIndex:0,
			//超参数
			selected:'0',
		   	options: [
			   	{ text: 'string', value: '0' },
			    { text: 'float', value: '1' },
			    { text: 'integer', value: '2' },
			    { text: 'boolean', value: '3' }
		   	],
		   	//数据标签
		   	selected_data:'0',
		   	options_data: [
			   	{ text: '数值型', value: '0' },
			    { text: '类别型', value: '1' },
		   	],
		   	//特征
		   	selected_feature:'0',
		   	options_feature: [
			   	{ text: 'integer', value: '0' },
			   	{ text: 'string', value: '1' }
		   	],
		   	num:0

    	}
    },
    components:{
    	headTop,
    	editor,
    	footerHtml,
    	'v-pagination': pagination
    },
    beforeRouteUpdate(to, from, next){
    	next();
    	//如果url的path=0代表模板，1代表模型，path=0并且id为-1是创建模板，path=1并且id为-1是创建模型
    	//path=0并且id不为-1，path=1并且id不为-1，代表是从详情页面点击进来的需要把editor更改并显示参数内容，
    	if(this.$route.params.path==0 && this.$route.params.id==-1){
    		location.reload();
    		this.diff_model_tem=true;
   		}else if(this.$route.params.path==1 && this.$route.params.id==-1){
 			location.reload();
    		this.diff_model_tem=false;
    	}
    },
    mounted(){
    	let editor = ace.edit("code"),
            theme = "github",
            language = "python";
        editor.setTheme("ace/theme/" + theme);
        editor.session.setMode("ace/mode/" + language);
        editor.setFontSize(14);
        editor.setReadOnly(false);
        editor.setOption("wrap", "free")
        ace.require("ace/ext/language_tools");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        if(this.$route.params.path==0 && this.$route.params.id==-1){
//  		location.reload();
    		this.diff_model_tem=true;
   		}else if(this.$route.params.path==1 && this.$route.params.id==-1){
// 			location.reload();
    		this.diff_model_tem=false;
    		this.tem_or_model_name='型';
    	}else if(this.$route.params.path==0 && this.$route.params.id!=-1){
    		this.diff_model_tem=true;
    		let sendData={
    			id:this.$route.params.id
    		}
			urlGetDetail(sendData).then(response => {
	  			if(response.data.code==200){
	  				this.addCode=response.data.data.code;
	  				editor.setValue(this.addCode);
	  				this.inputTemName=response.data.data.name;
	  				//设置的参数展示
//	  				if(response.data.data.param_spec!={}){
//		  				let resGetDataJson=response.data.data.param_spec,
//		  				    self1=this;
//		  				$.each(resGetDataJson.properties, function(key,val) {
//						    self1.parameterArr.push({
//								name:key,
//								selected:val.type,
//								default:val.default
//							})
//						});
//	  				};
					//设置的超参数展示
					this.resProperties=response.data.data.hyper_param_spec;
					if(this.resProperties!={}){
					let resGetDataJsonHyper=response.data.data.hyper_param_spec,
		  				selfHyper=this;
		  				$.each(resGetDataJsonHyper.properties, function(key,val) {
						    selfHyper.hyperParameterArr.push({
								name:key,
								selected:val.type,
								default:val.default
							})
						});
					}
	  			}else if(response.data.code!=200){
	  				console.log('获取数据失败')
	  			}
	     	});
    	}else if(this.$route.params.path==1 && this.$route.params.id!=-1){
    		this.diff_model_tem=false;
    		let sendData={
    			id:this.$route.params.id
    		}
			urlGetDetail(sendData).then(response => {
	  			if(response.data.code==200){
	  				this.addCode=response.data.data.code;
	  				editor.setValue(this.addCode);
	  			}else if(response.data.code!=200){
	  				console.log('获取数据失败')
	  			}
	     	});
    	}
    },
    methods: {
    	//点击notebook打开一个新的页面
    	_blankNotebook(){
    		urlNotebook().then(response => {
     			if(response.data.code==200){
	              	console.log('现在要去发送拿url的请求');
	              	this.linkSocket()
     			}else{
     				alert('返回数据有误')
     			}
           })
    	},
    	//判断int或者float
    	pregFloat(){
    		if(!/^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$/.test(this.fillInDefault)){
    			this.floatIntTip=true;
				this.typeTipMsg='只能输入浮点数和0';
			}else{
				this.floatIntTip=false;
			}
    	},
    	pregInt(){
			if(! /^-?\d+$/.test(this.fillInDefault)){
				this.floatIntTip=true;
        this.typeTipMsg='只能输入整数和0';
			}else{
				this.floatIntTip=false;
			}
		},
    	changeFillDefaultT(){
    		this.fillInDefault='true';
    	},
    	changeFillDefaultF(){
    		this.fillInDefault='false';
    	},
    	bombBoxHide(){
    		this.seen=false;
			this.seenSet=false;
			this.showSaveTem=false;
			this.bombChooseData=false;
    	},
    	chooseData(){
    		this.seen=true;
    		this.loadDataList();
    		this.bombChooseData=true;
    	},
    	pagechange:function(currentPage){
	      	this.dataAll.page_num=currentPage
	    // ajax请求, 向后台发送 currentPage, 来获取对应的数据
	      	this.loadDataList();
	    },
    	loadDataList(){
    		let sendData={
				page:this.dataAll.page_num,
				filter:this.dataAll.filter,
				owner:0
			};
    		//JOB表格数据
     		urlDashDataList(sendData).then(response => {
     			if(response.data.code==200){
	              	this.dataAll.data_all_list=response.data.data.items;
	            	this.dataAll.total=response.data.data.pagination*5;
     			}else{
     				alert('返回数据有误')
     			}
           })
    	},
    	changeDataId(id){
    		this.change_data_id=id;
    	},
    	compSelection(){
    		this.seen=false;
    		this.bombChooseData=false;
    	},
		codeCheckout(){
			console.log(this.inputCode=ace.edit("code").getValue())
		},
		changeHeaderState(){
			if(this.checkHeader==true){
				this.headerState=1;
				this.containTags=true;
			}else{
				this.headerState=0;
				this.containTags=false;
			}
		},
		addFeaturesItem(){
			this.features.push(this.sv);
			this.other_features_list.push({a:'',b:''})
		},
		addParameterItem(path){
			this.seen=true;
			this.seenSet=true;
			this.path=path;
		},
		addClassFun: function(index) {
			console.log(this.addClassIndex)
			this.addClassIndex = index;
		},
		synchronization(){
//			$('.saveTemBtn,.testTemBtn').removeAttr('disabled');
			this.seen=false;
			this.seenSet=false;
			if(this.path==1){
				//设置参数
				this.parameterArr.push({
					//自己定义
					name:this.fillInName,
					selected:this.selected,
					default:this.fillInDefault
				})
				//拼装成这种格式：{"type":"object","properties":{ "KEY1":{"type":"string","enum":["1"],"default":"1"},"KEY2"{"type":"number","minimum":"1","maximum":"10","default":"1"}}}
				this.param_spec['type'] = 'object';
				if(typeof(this.param_spec['properties']) == 'undefined'){
					this.param_spec['properties']= {};
				}
				var btnType =this.selected;
				switch(btnType){
					case '0'://字符串
						var data = {};
						data['type'] = 'string';
						data['enum'] = this.fillInRange.split(",");
						data['default'] = this.fillInDefault;
						this.param_spec['properties'][this.fillInName]=data;
						break;
					case '1'://float
						var data = {};
						data['type'] = 'number';
						data['minimum'] = (Number(this.fillInMin));
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.param_spec['properties'][this.fillInName]=data;
						break;
					case '2'://整型
						var data = {};
						data['type'] = 'integer';
						data['minimum'] = (Number(this.fillInMin));
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.param_spec['properties'][this.fillInName]=data;
						break;
					case '3'://boolean
						var data = {};
						data['type'] = 'boolean';
						data['default'] = eval(this.fillInDefault.toLowerCase());
						this.param_spec['properties'][this.fillInName]=data;
						break;
				}
			}else if(this.path==2){
				//设置超参数点击同步到左边
				this.hyperParameterArr.push({
					//自己定义
					name:this.fillInName,
					selected:this.selected,
					default:this.fillInDefault
				})
				this.hyper_param_spec['type'] = 'object';
				if(typeof(this.hyper_param_spec['properties']) == 'undefined'){
					this.hyper_param_spec['properties']= {};
				}
				var btnType =this.selected;
				switch(btnType){
					case '0'://字符串
						var data = {};
						data['type'] = 'string';
						data['enum'] = this.fillInRange.split(",");
						data['default'] = this.fillInDefault;
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
					case '1'://float
						var data = {};
						data['type'] = 'number';
						data['minimum'] = (Number(this.fillInMin));
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
					case '2'://整型
						var data = {};
						data['type'] = 'integer';
						data['minimum'] = (Number(this.fillInMin));
						data['maximum'] = (Number(this.fillInMax));
						data['default'] = (Number(this.fillInDefault));
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
					case '3'://bool
						var data = {};
						data['type'] = 'boolean';
						data['default'] = eval(this.fillInDefault.toLowerCase());
						this.hyper_param_spec['properties'][this.fillInName]=data;
						break;
				}
			}
		},
		showSave(show_save){
			this.seen=true;
			this.showSaveTem=true;
			this.show_save=show_save;
		},
		SaveOrReleaseTemplate(){
			this.seen=false;
			this.showSaveTem=false;
			let data_spec={},
				label={},
				feature={};
			label[this.labelName]=this.selected_data;
			$(".features_box").each(function(i,n){
				feature[$(n).children('input').val()]=$(n).children('select').val()
			});
			//拼装data_spec 的格式
			data_spec['need_label'] = this.headerState;
			data_spec['label'] =label;
			data_spec['features'] =feature;
	    	let sendData={
		  		name:this.inputTemName,
		  		description:this.inputTemDes,
		  		visible:this.editVis,
				type:0,
				content:this.inputCode=ace.edit("code").getValue(),
//				params:'{}',
				param_spec:JSON.stringify(this.param_spec),
				hyper_param_spec:JSON.stringify(this.hyper_param_spec),
				data_spec:data_spec,
	    	};
			if(this.inputTemDes==''){
				this.seenTemTip=true;
			}else{
				this.seenTemTip=false;
				//show_save==1为保存，2为发布
				if(this.show_save==1 && this.$route.params.id==-1){
			    	urlSaveTemplate(sendData).then(response => {
			  			if(response.data.code==200){
			  				this.saveSuccess=true;
			  				this.templateId=response.data.data.template_id;
			  				let self=this;
		     				setTimeout(function(){
		     					self.$router.push({name:"templateDetail",params:{id:self.templateId}});
		     				}, 2000);
			  			}else if(response.data.code==201){
			  				this.errorTip=response.data.message;
			  				this.saveError=true;
			  			}
		     		});
				}else if(this.$route.params.id!=-1){
					let sendData={
			    		id:this.$route.params.id,
				  		name:this.inputTemName,
				  		description:this.inputTemDes,
				  		visible:this.editVis,
						type:0,
						content:this.inputCode=ace.edit("code").getValue(),
		//				params:'{}',
						param_spec:JSON.stringify(this.param_spec),
						hyper_param_spec:this.resProperties
			    	};
					//编辑源文件之后再把数据发送给后台
					urlUpdateTemplate(sendData).then(response => {
						if(response.data.code==200){
			  				this.saveSuccess=true;
			  				let self=this;
		     				setTimeout(function(){
		     					self.$router.push({name:"templateDetail",params:{id:self.$route.params.id}});
		     				}, 2000);
			  			}else if(response.data.code==201){
			  				this.errorTip=response.data.message;
			  				this.saveError=true;
			  			}
					})
				}
			}
		},
		testTemplate(){
			let data_spec={},
				label={},
				feature={};
			label[this.labelName]=this.selected_data;
			$(".features_box").each(function(i,n){
				feature[$(n).children('input').val()]=$(n).children('select').val()
			});
			//拼装data_spec 的格式
			data_spec['need_label '] = this.headerState;
			data_spec['label'] =label;
			data_spec['features'] =feature;
	    	let sendData={
		  		name:this.inputTemName,
		  		description:this.inputTemDes,
		  		visible:this.editVis,
				type:0,
				content:this.inputCode=ace.edit("code").getValue(),
				//params:'{}',
				param_spec:JSON.stringify(this.param_spec),
				hyper_param_spec:JSON.stringify(this.hyper_param_spec),
				data_spec:data_spec,
				data_id:this.change_data_id,
				content:this.inputCode=ace.edit("code").getValue(),
				tag_col:'',
				cols:'',
	    	};
	    	urlTestTemplate(sendData).then(response => {
	  			if(response.data.code==200){
					this.linkSocket();
	  			}else if(response.data.code!=200){
	  				console.log('获取数据失败')
	  			}
	 		}).catch(error => {
            	if(error.response.data.code==401){
            		localStorage.clear();
            		this.$router.replace('/login');
				}
            });
		},
		linkSocket(){
			let socket = io.connect(global_.urlSocket),
	            user = localStorage.getItem('username');
	        socket.emit('join', {'room': user});
			let _selfRun=this;
	        socket.on('my_response', function(res) {
//	        	console.log(res.type)
	            //链接状态
	            if(res.type==0){
	            	if(res.type==0 && res.code==1){
	            		console.log('链接成功')
	            	}else if(res.type==0 && res.code!=1){
		                console.log('connect failed');
		            }
	            }
	            //已经加入到聊天室
	            if(res.type==1){
	            	console.log(res.data)
	            }
	            //所有人都能收到的消息
	            if(res.type==2){
	            	console.log(res.data)
	            }
	            //单播消息
	            if(res.type==3){
	            	if(res.code==0 && res.type==3){
	            		console.log('执行中')
	            	}else if(res.code==3 && res.type==3){
	            		//进入到模板测试
	            		console.log(res.data)
	            		_selfRun.runResult=res.data

	            	}else if(res.code==6 && res.type==3){
	            		//进入到模板notebook
	            		this.num+=1;
	            		console.log(this.num)
	            		if(this.num==1){
	            			window.open(res.data)
	            		}
	            	}
	            }
	        });

	        //接收广播
	        socket.on('broadcast', function(msg){
		            console.log(msg.data);
	        });
		}
  	}
}
</script>


<style lang="css">
	@import "../assets/css/base.css"
</style>
<style lang="css">
	@import "../assets/css/createTemplate.css"
</style>
<style lang="css">
	@import "../assets/css/data_info.css"
</style>
